const fs = require("fs");
const axios = require("axios");
const CryptoJS = require("crypto-js");
const querystring = require("querystring");
const translateList = require("./config/lang");
const { _appKey, _appSecret } = require('./config/index')
const appKey = _appKey;
const key = _appSecret; // 注意：保护好您的appSecret，避免泄露
const vocabId = "您的用户词表ID";
let originLang = 'zh'; // 默认语言 中文转其他
// 获取对应的语言项 默认为中文
function getItem(lang,origin = originLang) {
  let _translateList;
  if(origin != 'zh') {
    // 修改本地数组
    _translateList = translateList.map(item =>{
      return {
        lang:item.lang.replace('中文',originLang), // 代表其他语言转为目标语言
        value:item.value.replace('zh-CHS',origin) // 替换中文value值为其他语言
      }
    })
  } else {
    _translateList = translateList; 
  }
  return _translateList.find((item) => {
    return item.lang.includes(lang) && item.value.startsWith(origin);
  });

}




// 截断函数保持不变
function truncate(q) {
  const len = q.length;
  if (len <= 20) return q;
  return q.substring(0, 10) + len + q.substring(len - 10, len);
}

// 中文翻译为其他语言
async function translateLang(queries, to) {
  console.log(queries);
  return new Promise(async (resolve, reject) => {
    const salt = Date.now();
    const curtime = Math.floor(Date.now() / 1000);
    const params = getItem(to).value.split("2");
    const combinedQueries = queries.join("");
    const str1 = appKey + truncate(combinedQueries) + salt + curtime + key;
    const sign = CryptoJS.SHA256(str1).toString(CryptoJS.enc.Hex);

    const data = {
      q: queries,
      appKey: appKey,
      salt: salt,
      from: params[0], // 英文设置为en
      to: params[1],
      sign: sign,
      signType: "v3",
      curtime: curtime,
      vocabId: vocabId,
    };

    try {
      const response = await axios.get(
        `https://openapi.youdao.com/v2/api?${querystring.stringify(data)}`
      );
      console.log(response.data);
      const results = response.data.translateResults || "";

      // 确保结果数组与输入查询一一对应
      const translatedItems = queries.map((query, index) => ({
        original: query,
        translated: results[index] ? results[index].translation : "",
      }));

      resolve(translatedItems);
    } catch (error) {
      console.error("Error:", error);
      reject(error);
    }
  });
}

// 分批处理翻译的辅助函数
async function batchTranslate(stringsArray, batchSize, targetLang) {
  const batches = [];
  for (let i = 0; i < stringsArray.length; i += batchSize) {
    batches.push(stringsArray.slice(i, i + batchSize));
  }

  let translatedItems = [];
  for (let batch of batches) {
    const batchTranslations = await translateLang(batch, targetLang);
    translatedItems = translatedItems.concat(batchTranslations);
    // 在批次间添加延时，根据需要调整延时时间，例如 3000 毫秒
    await new Promise((resolve) => setTimeout(resolve, 3000));
  }
  return translatedItems;
}

// 修改 translateJsonFile 函数以使用分批翻译
async function translateJsonFile(
  inputFilePath,
  outputFilePath,
  targetLang,
  batchSize = 100
) {
  try {
    const jsonData = JSON.parse(fs.readFileSync(inputFilePath, "utf8"));

    // 找出所有需要翻译的字符串，组成数组
    const allStringsToTranslate = [];
    function collectStrings(obj) {
      if (typeof obj === "string") {
        allStringsToTranslate.push(obj);
      } else if (Array.isArray(obj)) {
        obj.forEach((item) => collectStrings(item));
      } else if (typeof obj === "object" && obj !== null) {
        Object.values(obj).forEach((value) => collectStrings(value));
      }
    }
    collectStrings(jsonData);

    // 分批翻译
    const translatedItems = await batchTranslate(
      allStringsToTranslate,
      batchSize,
      targetLang
    );

    // 将翻译结果回填到原始JSON对象中
    function replaceStrings(obj) {
      if (typeof obj === "string") {
        const foundTranslation = translatedItems.find(
          (item) => item.original === obj
        );
        return foundTranslation ? foundTranslation.translated : obj;
      } else if (Array.isArray(obj)) {
        return obj.map((item) => replaceStrings(item));
      } else if (typeof obj === "object" && obj !== null) {
        return Object.fromEntries(
          Object.entries(obj).map(([key, value]) => [
            key,
            replaceStrings(value),
          ])
        );
      }
      return obj;
    }

    const translatedData = replaceStrings(jsonData);

    fs.writeFileSync(
      outputFilePath,
      JSON.stringify(translatedData, null, 2),
      "utf8"
    );
    console.log(`Translation complete. File saved as ${outputFilePath}`);
  } catch (error) {
    console.error("Error during translation or file operation:", error);
  }
}

// 调用函数，示例：将'source.json'从英文翻译成中文并保存为'translated.json'
// translateJsonFile("cn.json", "translated.json", "繁体");
// translateJsonFile("cn.json", "translated.json", "英语");

// 测试其他语言 需要修改originLang的值
// 必须与translateJsonFile第一个参数传入的语言保持一致
originLang = 'en'; 
translateJsonFile("en.json", "translated.json", "希腊语");

